package com.yanqu.road.server.cross.service;

import com.google.protobuf.AbstractMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.syncMessage.SyncMessage;
import com.yanqu.road.pb.syncMessage.SyncUnion;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.command.ICrossServiceCommand;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

public class UnionRankTopICrossServiceCmd implements ICrossServiceCommand {
    @Override
    public CompletableFuture<AbstractMessage.Builder<?>> execute(SyncMessage.Request request) throws InvalidProtocolBufferException {
        SyncUnion.UnionRankTopResponse.Builder unionRankTopResponseBuilder = SyncUnion.UnionRankTopResponse.newBuilder();
        long serverId = request.getRawServerId();
        int groupId = CrossUnionServerGroupMgr.getGroupIdByServerId(serverId);
        Set<Long> serverIdSet = CrossUnionServerGroupMgr.getGroupServer(groupId);
        List<CrossUnionInfo> dataList = CrossUnionMgr.getUnionListByServerList(serverIdSet);

        dataList.sort((o1, o2) -> o2.getTotalEarnSpeed().compareTo(o1.getTotalEarnSpeed()));

        CrossUnionInfo crossUnionInfo = dataList.stream().findFirst().orElse(null);
        if (crossUnionInfo != null) {
            unionRankTopResponseBuilder.setUnionUid(crossUnionInfo.getUnionUid());
            UnionProto.UnionBaseTempMsg.Builder unionBaseTempMsg = UnionBasePb.parseUnionBaseTempMsg(CrossUnionMgr.parseUnionBaseInfo(crossUnionInfo));
            unionRankTopResponseBuilder.setUnionBaseData(unionBaseTempMsg);
        } else {
            unionRankTopResponseBuilder.setUnionUid("");
        }
        CompletableFuture<AbstractMessage.Builder<?>> completableFuture = new CompletableFuture<>();
        completableFuture.complete(unionRankTopResponseBuilder);
        return completableFuture;
    }
}
